package com.koron.common.core.business.datadict.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.bean.util.ServletUtils;
import com.koron.common.core.business.datadict.bean.po.SysDataDict;
import com.koron.common.core.business.datadict.bean.po.SysDataDictDetail;
import com.koron.common.core.business.datadict.service.SysDataDictService;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.util.SpringUtils;
import org.koron.ebs.mybatis.ADOConnection;
import org.springframework.context.ApplicationContext;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据字典静态工具类
 * @author jzp
 * @since 2021/10/15
 */
public class DataDictTool {
    private static SysDataDictService dictService;

    static{
        ApplicationContext applicationContext = SpringUtils.getApplicationContext();
        if (applicationContext != null) {
            dictService = applicationContext.getBean(SysDataDictService.class);
        }
    }
    /**
     * 根据字典编码查询字典详情数据
     * tip:
     * 字典编码不能重复
     *
     * @param code 字典编码
     * @return map
     * key: key 后端使用
     * value: value 前端使用
     */
    public static Map<String, String> getDataDictByCode(String classifyCode, String code) {
        if (dictService == null) {
            ApplicationContext applicationContext = SpringUtils.getApplicationContext();
            if (applicationContext == null) {
                return new HashMap<>();
            }
            dictService = applicationContext.getBean(SysDataDictService.class);
        }
        SysDataDict sysDataDict = ADOConnection.runTask(dictService, "getByClassifyIdAndCode", SysDataDict.class, classifyCode, code);
        List<SysDataDictDetail> sysDataDictDetailList = sysDataDict.getSysDataDictDetailList();

        EamUser eamUser = ThreadLocalContext.get();
        // 当前语种
        String language = ServletUtils.getRequest().getHeader("Language");
        String appId = eamUser.getAppId();
        if (StrUtil.isEmpty(appId)) {
            appId = "";
        }
        Map<String, String> map = new HashMap<>();
        // 如果没有私有配置则使用公共配置
        for (SysDataDictDetail sysDataDictDetail : sysDataDictDetailList) {
            if (StrUtil.isNotBlank(language) && StrUtil.isNotBlank(sysDataDictDetail.getLang())) {
                sysDataDictDetail.setValue(JSONUtil.toBean(sysDataDictDetail.getLang(), Map.class).get(language).toString());
            }
            // 如果是当前数据租户
            if (appId.equals(sysDataDictDetail.getAppid())) {
                map.put(sysDataDictDetail.getKey(), sysDataDictDetail.getValue());
            } else if (StrUtil.isEmpty(sysDataDictDetail.getAppid()) || "0".equals(sysDataDictDetail.getAppid())) {
                // 如果是公共租户
                map.putIfAbsent(sysDataDictDetail.getKey(), sysDataDictDetail.getValue());
            }
        }
        return map;
    }

}
